/*
 * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dhcp_c_adapter.h"
#include "dhcp_c_api.h"
#include "securec.h"

bool CallAdapterSetRange(std::string &ipAddr, const std::string &ifaceName)
{
    std::string::size_type pos = ipAddr.find(".");
    if (pos == std::string::npos) {
        return false;
    }
    std::string ipHead = ipAddr.substr(0, pos);
    std::string subnet = "255.255.255.0";
    std::string p2p = "p2p";

    DhcpRange range;
    if (strcpy_s(range.strStartip, INET_ADDRSTRLEN, (ipHead + ".3").c_str()) != EOK
        ||strcpy_s(range.strEndip, INET_ADDRSTRLEN, (ipHead + ".254").c_str()) != EOK
        ||strcpy_s(range.strSubnet, INET_ADDRSTRLEN, subnet.c_str()) != EOK) {
        return false;
    }
    range.iptype = 0;
    std::string tagName = ifaceName;
    transform(tagName.begin(), tagName.end(), tagName.begin(), ::tolower);
    if (tagName.find("p2p") != std::string::npos) {
        if (PutDhcpRange(range.strTagName, &range) != 0) {
            return false;
        }
        if (SetDhcpRange(ifaceName.c_str(), &range) != 0) {
            return false;
        }
    } else {
        if (strcpy_s(range.strTagName, INET_ADDRSTRLEN, ifaceName.c_str()) != EOK) {
            return false;
        }
        if (SetDhcpRange(ifaceName.c_str(), &range) != 0) {
            return false;
        }
    }
    return true;
}